"use client";
import { AntdRegistry } from "@ant-design/nextjs-registry";
import "./globals.css";
import React, { useCallback, useEffect } from "react";
import { BasicLayout } from "@/layouts/BasicLayout";
import { Provider, useDispatch } from "react-redux";
import stores, { AppDispatch } from "@/stores";
import { getLoginUserUsingGet } from "@/api/userController";
import { setLoginUser } from "@/stores/loginUser";
import { usePathname } from "next/navigation";
import { writeList } from "../../constant/writeList";
import AccessLayout from "@/access/AccessLayout";

const GlobalInitLogic: React.FC<
  Readonly<{
    children: React.ReactNode;
  }>
> = ({ children }) => {
  const dispatcher = useDispatch<AppDispatch>();
  const pathname = usePathname();

  // callback钩子可以缓存
  const doInitLogin = useCallback(async () => {
    const res = await getLoginUserUsingGet();
    if (res.data) {
      const userData = res.data.data;
      dispatcher(setLoginUser({ ...userData }));
    }
  }, []);

  // useEffect钩子执行一次
  useEffect(() => {
    doInitLogin();
  }, []);

  return children;
};

export default function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="zh">
      <body>
        <AntdRegistry>
          <Provider store={stores}>
            <GlobalInitLogic>
              <BasicLayout>
                <AccessLayout>{children}</AccessLayout>
              </BasicLayout>
            </GlobalInitLogic>
          </Provider>
        </AntdRegistry>
      </body>
    </html>
  );
}
